package com.zhz.mall.common.util;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import java.util.Objects;

/**
 * EnvironmentUtils
 * <p>
 * Spring Environment 工具类
 *
 * @author zhouhengzhe
 */
public abstract class EnvironmentUtils {


    private static Environment environment;



    public static Environment getEnvironment() {
        return getEnvironment(true);
    }


    public static Environment getEnvironment(boolean required) {
        if (Objects.isNull(environment)) {
            ApplicationContext applicationContext = SpringUtil.getApplicationContext();
            if (Objects.nonNull(applicationContext)) {
                environment = applicationContext.getBean(Environment.class);
            }
            if (required && Objects.isNull(environment)) {
                throw new IllegalStateException("the environment is not prepared");
            }
        }
        return environment;
    }


    public static String getProperty(String key) {
        return getEnvironment().getProperty(key);
    }


    public static String getProperty(String key, String defaultValue) {
        return getEnvironment().getProperty(key, defaultValue);
    }


    public static <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        return getEnvironment().getProperty(key, targetType, defaultValue);
    }


}
